package com.knowledge.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zzz
 * @title: TemplateParserUtil
 * @projectName blog-api
 * @description: TODO
 * @date 2022/3/416:10
 */
public class TemplateParserUtil {

    private static final String startTag = "${";

    private static final String endTag = "}";

    private static final Pattern pattern = Pattern.compile("\\$\\{[\\w]+\\}") ;

    /**
    　* @description: 内容解析
    　* @param ${tags}
    　* @author zzz
    　* @date 2022/3/4 16:23
    */
    public static String parse(String template, Map<String, String> map){
        StringBuffer temp = new StringBuffer(template);
        Map<String, String> tagMap = getTagIndex(template);
        for(Map.Entry<String, String> entry : tagMap.entrySet()){
            //获得标识符
            String tag = entry.getValue();
            //获得替换的值，如果没有，则不变
            String repVal = map.get(entry.getKey())==null?entry.getValue():map.get(entry.getKey());
            //获得标识符在字符串中出现的次数
            int index = 0;
            //判断同一个标识符在字符串中出现的次数
            while((index=template.indexOf(tag,index))!=-1){
                //替换
                temp = temp.replace(temp.indexOf(tag), temp.indexOf(tag)+tag.length(), repVal);
                index += tag.length();
            }
        }
        return temp.toString();
    }

    private static Map<String, String> getTagIndex(String template){
        Map<String, String> map = new HashMap();
        Matcher matcher = pattern.matcher(template);
        int startLen = startTag.length();
        while(matcher.find()){
            //获得标示符
            String tag = matcher.group();
            //获得key
            String key = tag.substring(startLen, tag.lastIndexOf(endTag));
            map.put(key, tag);
        }
        return map;
    }
}
